package com.jayqqaa12.system.controller;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jayqqaa12.jbase.util.Txt;
import com.jayqqaa12.jbase.util.Validate;
import com.jfinal.ext.plugin.sqlinxml.SqlKit;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.TableMapping;

/***
 * 
 * @author 12
 *
 * @param <M>
 */
public class TreeModel<M extends com.jfinal.plugin.activerecord.Model<M>> extends com.jayqqaa12.jbase.jfinal.ext.model.Model<M> {

 

	/***
	 * 把 model 转化为 list 找到其中的单个属性
	 * 
	 * @param sql
	 * @param attr
	 * @return
	 */
	public List<String> getAttr(String sql, String attr, Object ... param) {

		List<String> list = new ArrayList<String>();

		for (M t : this.find(sql, param)) {

			list.add(t.getStr(attr));
		}
		return list;

	}
	
 

	
	public List<M> listOrderBySeq(String where, Object... params) {

		return findAllByWhere(where + " order by seq", params);
	}

	/***
	 * 删除自己的同时 删除 所有 子节点 属性名 必需为pid
	 * 
	 */
	public boolean deleteByIdAndPid(Object id) {
		boolean result = deleteById(id);

		List<TreeModel> list = (List<TreeModel>) findAllByWhere("where pid=?", id);

		for (TreeModel m : list) {
			deleteByIdAndPid(m.getId());

			Db.update("delete from " + tableName + " where pid=? ", id);
		}

		return result;
	}

	 
	public boolean pidIsChild(Object id, Integer pid) {
		boolean result = false;
		if (pid != null) {
			List<TreeModel> list = (List<TreeModel>) findAllByWhere(" where  pid =?  ", id);

			if (list.size() == 0) result = false;

			for (TreeModel r : list) {
				if (pid.equals(r.getId())) {
					result = true;
					return result;
				} else {
					if (pidIsChild(r.getId(), pid)) {
						result = true;
						return result;
					}
				}

			}
		}

		return result;

	}

	 

}
